//
//  TempLDExt.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/7/12.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit
var LdresultCache:[String:[String:Any]?] = [:]
// MARK: 联动功能
// 联动数据量一般比较大，做一个缓存，单次登录只加载一次
extension ConfigMenuForm {
    // 显示字段示例      proName;cityName;dictName
    
    
    func configLDData(oneD:TemplateModel,indexPath:IndexPath?,numOfc:Int) {

        
        // 联动
        self.comPick!.numberOfComponents = numOfc
        
        self.comPick!.numberOfRowsInComponentClo = { com in
            if com == 0 {
                return self.ldShowArr.count
            } else if com == 1 {
                return self.ldShowArr[self.selected1].child.count
            } else if com == 2 {
                return self.ldShowArr[self.selected1].child[self.selected2].child.count
            } else {
                return 0
            }
        }
        
        self.comPick!.titleForRowClo = { com,row in
            
            if com == 0 {
                
                let show1 = self.ldShowArr[row].ldShowParam
                TempLog( "\(com) - \(row) \(show1)")
                return show1
            } else if com == 1 {
                let show2 = self.ldShowArr[self.selected1].child[row].ldShowParam
                TempLog( "\(com) - \(row) \(show2)")
                return show2
                
            } else if com == 2 {
                let show3 = self.ldShowArr[self.selected1].child[self.selected2].child[row].ldShowParam
                TempLog( "\(com) - \(row) \(show3)")
                return show3
            } else {
                return ""
            }
            
        }
        self.comPick!.didSelectRowClo = { com,row in
            if com == 0 {
                self.selected1 = row
                self.selected2 = 0
                self.comPick!.selectA(comp:1, row: self.selected2)
                if self.comPick!.numberOfComponents == 3 {
                    self.selected3 = 0
                    self.comPick!.selectA(comp: 2, row: self.selected3)
                }
            } else if com == 1 {
                self.selected2 = row
                if self.comPick!.numberOfComponents == 3 {
                    self.selected3 = 0
                    self.comPick!.selectA(comp:2, row: self.selected3)
                }
            } else if com == 2 {
                self.selected3 = row
            }
            
        }
        self.comPick!.resultClosure = {
            
            for i in 0..<oneD.lovLDBackFillArr.count {
                let bOne = oneD.lovLDBackFillArr[i]
                let spA = bOne.components(separatedBy: ",")
                //bOne 示例： province:startPro,city:startCity,district:startDicstrict
                for item in spA {
                    let pre = item.preChar(char: ":").unwrap.replacingOccurrences(of: "b.", with: "")
                    let suf = item.sufChar(char: ":").unwrap
                    
                    if i == 0 {
                        let dicX = self.ldShowArr[self.selected1].dic
                        if indexPath.isSome {
                            self.detHandler[self.cDIndex][indexPath!.section].dic[suf] = dicX[pre]
                        } else {
                            self.main[suf] = dicX[pre]
                        }
                        
                        
                    } else if i == 1 {
                        let dicX = self.ldShowArr[self.selected1].child[self.selected2].dic
                        if indexPath.isSome {
                            self.detHandler[self.cDIndex][indexPath!.section].dic[suf] = dicX[pre]
                        } else {
                            self.main[suf] = dicX[pre]
                        }
                    } else if i == 2 {
                        let dicX = self.ldShowArr[self.selected1].child[self.selected2].child[self.selected3].dic
                        if indexPath.isSome {
                            self.detHandler[self.cDIndex][indexPath!.section].dic[suf] = dicX[pre]
                        } else {
                            self.main[suf] = dicX[pre]
                        }
                        
                        
                    }
                }
            }
            
            if indexPath.isSome {
                self.reloadDetData(indexPath:indexPath)
                
            } else {
                self.configTempDataSource()
               
            }
            
            
        }
        self.comPick!.reloadAllComp()
    }
    // 联动的显示
    func showLiandong(oneD:TemplateModel,indexPath:IndexPath?) {
     
       //重新创建，互不影响
         comPick = KSComPicker(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: KSGlobal.screenH),multiSelect: oneD.is_multichoice == "1")
       
       
        
        
        var detDic:[String:Any]?
        if indexPath.isSome {
            detDic = self.detHandler[self.cDIndex][indexPath!.section].dic
        }
        
        let pathDic = url2PathDic(mainDic: self.main,currDetaiDic: detDic,arr: oneD.pathHandler.comPa)
 
        if let cacheR =  LdresultCache[oneD.pathHandler.path] {
       
             dealRes(infoDic: cacheR)
        } else {
         
            netW()
        }
        func dealRes(infoDic:[String:Any]?) {
      
             var numOfc = 0
            if let lel1 =  infoDic?[TKey.levelInfos1] as? [[String : Any]],
               lel1.count > 0,
               oneD.lovLDShowArr.count > 0 {
                self.ldOriArr = lel1.compactMap{ LianDHandler(dic: $0,ldShowParam:any2Str($0[oneD.lovLDShowArr[0]])) }
                numOfc = 1
            }
            if let lel2 =  infoDic?[TKey.levelInfos2] as? [[String : Any]],
               lel2.count > 0, oneD.lovLDShowArr.count > 1 {
                
                for i in 0..<self.ldOriArr.count {
                    let item1 = self.ldOriArr[i]
                    let filterArr = lel2.filter { any2Str($0[oneD.lovLDShowArr[0]]) == item1.ldShowParam }
                    self.ldOriArr[i].child = filterArr.compactMap{ LianDHandler(dic: $0,ldShowParam:any2Str($0[oneD.lovLDShowArr[1]])) }
                }
                numOfc = 2
            }
            if let lel3 =  infoDic?[TKey.levelInfos3] as? [[String : Any]],
               lel3.count > 0,
               oneD.lovLDShowArr.count > 2 {
                
                for i in 0..<self.ldOriArr.count {
                    let item1 = self.ldOriArr[i]
                    for y in 0..<item1.child.count {
                        let item2 = item1.child[y]
                        let filterArr = lel3.filter { any2Str($0[oneD.lovLDShowArr[1]]) == item2.ldShowParam }
                        self.ldOriArr[i].child[y].child = filterArr.compactMap{ LianDHandler(dic: $0,ldShowParam:any2Str($0[oneD.lovLDShowArr[2]])) }
                    }
                }
                numOfc = 3
            }
            
            // 子数组匹配到，自己也添加
            func findChild(_ one:LianDHandler,key:String) -> LianDHandler? {
                var newA: [LianDHandler] = []
                for item in one.child {
                     if item.ldShowParam.contains(key) {
                        newA.append(item)
                         continue
                    }
                    let optionItem = findChild(item, key: key)
                    if optionItem.isSome {
                        newA.append(optionItem!)
                    }
                }
                 if newA.count > 0 {
                    var newOne = one
                    newOne.child = newA
                    return newOne
                } else {
                    return nil
                }
            }
            
            self.comPick!.searchClo = { str in
              
                    if str != "" {
                         var filteredLD: [LianDHandler] = []
                        
                        for item in self.ldOriArr {
                            if item.ldShowParam.contains(str) {
                                filteredLD.append(item)
                                continue
                            }
                             let optionItem = findChild(item, key: str)
                            if optionItem.isSome {
                                filteredLD.append(optionItem!)
                            }
                        }
                   
                        self.ldShowArr = filteredLD
                        
                    } else {
                        self.ldShowArr = self.ldOriArr
                    }
                    
                
                self.selected1 = 0
                self.selected2 = 0
                self.selected3 = 0
                self.configLDData(oneD: oneD, indexPath: indexPath,numOfc: numOfc)
            }
            self.ldShowArr = self.ldOriArr
            self.selected1 = 0
            self.selected2 = 0
            self.selected3 = 0
            self.configLDData(oneD: oneD, indexPath: indexPath,numOfc: numOfc)
       
            if let kwindow =  UIApplication.shared.windows.filter({$0.isKeyWindow}).first {
                kwindow.rootViewController?.view.addSubview(self.comPick!)
            }
        }
        func netW() {
            KSNetwork.shared.doRequest(API.temp(.path(path: oneD.pathHandler.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    LdresultCache.updateValue(data.infoDic, forKey: oneD.pathHandler.path)
                    dealRes(infoDic: data.infoDic)
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }

        
        
    }
    
    
    
    
    
    
    
    
}
